<?php
namespace app\backmanage\controller;
use app\common\model\common\AnchorChangeMobileLogModel;
use thans\layuiAdmin\facade\AdminsAuth;
use thans\layuiAdmin\facade\Json;
use thans\layuiAdmin\facade\Utils;
use thans\layuiAdmin\model\Admins;
use thans\layuiAdmin\Traits\FormActions;
use think\facade\View;
use think\Request;
use app\common\model\common\Anchor as AnchorModel;

class AnchorChangeMobile extends Base{

    use FormActions;

    protected $route_alias = 'anchorChangeMobile';
    protected $title = '主播换绑手机号管理';

    public function list(Request $request)
    {
        if ($request->isAjax() || $request->isPost()) {
            list($where, $order, $page, $limit) = Utils::buildParams('front_mobile|after_mobile');
            $fontMobile = '';
            $afterMobile = '';
            foreach ($where as $key => $value) {
                if ($value[0] == 'front_mobile') {
                    unset($where[$key]);
                    $fontMobile=$value[2];
                }
                if ($value[0] == 'after_mobile') {
                    unset($where[$key]);
                    $afterMobile=$value[2];
                }
            }
            $model=(new AnchorChangeMobileLogModel());
            if ($fontMobile){
                $model=$model->where('front_mobile','=',$fontMobile);
            }
            if ($afterMobile){
                $model=$model->where('after_mobile','=',$afterMobile);
            }
            $list = $model->page($page, $limit)->order('create_time', 'desc')
                ->field('id,partition_id,front_mobile,after_mobile,remarks,create_time,admin_id')->select()->toArray();
            if($list){
                 $partitionConfigs=\app\common\model\common\PartitionPackage::where([
                    'status'=>1
                ])->column('partition_name','partition_id');
                foreach($list as &$item){
                    $item['partition_name']=$partitionConfigs[$item['partition_id']]??'';
                }
            }    
            //获取用户ID
            $infos=array_column($list,'admin_id','id');
            $adminIds=array_column($list,'admin_id');
            $admin=(new Admins())->whereIn('id',$adminIds)->column('nickname','id');
            foreach ($list as &$item){
                $adminId=$infos[$item['id']]??0;
                $item['admin_name']=$admin[$adminId]??'';
            }
            $count = $model->where($where)->count();
            Json::success('获取成功', $list, ['total' => $count, 'count' => $count]);
        } else {
            $data = [];
            $data['cols'] = [
                ['field' => 'id', 'title' => 'ID', 'sort' => true, 'width' => '8%'],
                ['field' => 'partition_id', 'title' => '分区号', 'width' => '8%'],
                ['field' => 'partition_name', 'title' => '分区名称', 'width' => '10%'],
                ['field' => 'front_mobile', 'title' => '原手机号', 'width' => '15%'],
                ['field' => 'after_mobile', 'title' => '换绑后手机号', 'width' => '15%'],
                ['field' => 'remarks', 'title' => '换绑说明', 'width' => '20%'],
                ['field' => 'admin_name', 'title' => '操作人', 'width' => '10%'],
                ['field' => 'create_time', 'title' => '操作时间', 'width' => '20%'],
            ];
            $data['title'] = $this->title;
            $data['search'][] = ['type' => 'text', 'field' => 'front_mobile', 'desc' => '请输入','title'=>'原手机号'];
            $data['search'][] = ['type' => 'text', 'field' => 'after_mobile', 'desc' => '请输入','title'=>'换绑后手机号'];
            //url init
            $data['list_url'] = '/backmanage/' . $this->route_alias . '/list';
            $create_url = '/backmanage/' . $this->route_alias . '/create';

            if (AdminsAuth::check($create_url)) {
                $data['create_url'] = $create_url;
            }
            return View::fetch('anchor_change_mobile/index', $data);
        }
    }

    public function create(Request $request)
    {
        if ($request->isPost()) {
            $param    = $request->all();
            if (empty($param['front_mobile'])) {
                return json(['code'=>-1,'msg'=>'原手机号不能为空']);
            }
            if (empty($param['after_mobile'])) {
                return json(['code'=>-1,'msg'=>'换绑后手机号不能为空']);
            }
            $member=AnchorModel::where([
                'mobile' => $param['front_mobile'],
                'status' =>1
            ])->order('id','desc')->find();
            if (empty($member->id)) {
                return json(['code'=>-1,'msg'=>'该手机号未注册']);
            }
            $afterMember=AnchorModel::where([
                'mobile'  => $param['after_mobile'],
                'status' =>1
            ])->order('id','desc')->find();
            if(!empty($afterMember->id) && $member->partition_id!=$afterMember->partition_id){
                return json(['code'=>-1,'msg'=>'新手机号和旧手机号未在同一分区内，请设置为统一分区在更换']);
            }
            $afterMemberMobile=$afterMember['mobile']??'';
            //获取分区数据
            $partitionInfo=\app\common\model\common\PartitionPackage::where([
                'partition_id'=>$member['partition_id'],
                'status'=>1
            ])->find();
            if(empty($partitionInfo->id)){
                Json::error('分区ID无效，请重试');
            }
            $subMemberModel=getSwitchDatabaseModel(sprintf("partition_%s",$partitionInfo['partition_id']),$partitionInfo['api_mysql_host_name'],$partitionInfo['api_mysql_database'],$partitionInfo['api_mysql_username'],$partitionInfo['api_mysql_password'],$partitionInfo['api_mysql_hostport']);
            try {
                $ret=$subMemberModel->table('member')->where([
                    'mobile' => $member['mobile'],
                    'status' =>1
                ])->update([
                    'account' => $param['after_mobile'],
                    'mobile'  => $param['after_mobile'],
                    'update_time' => time()
                ]);
                if(!$ret){
                    return json(['code' => -1, 'msg' => '变更失败', 'data' => '']);
                }
                //确定变更说明
                $remarks='换绑新手机号';
                if ($afterMemberMobile){
                    $ret=$subMemberModel->where([
                        'mobile' => $afterMemberMobile,
                        'status' =>1
                    ])->update([
                        'account' => $param['front_mobile'],
                        'mobile'  => $param['front_mobile'],
                        'update_time' => time()
                    ]);
                    if(!$ret){
                        return json(['code' => -1, 'msg' => '变更失败', 'data' => '']);
                    }
                    $remarks='已有账号手机号互换';
                }
                $data = [
                    'partition_id'     => $member['partition_id'],
                    'front_mobile'     => $param['front_mobile'],
                    'after_mobile'     => $param['after_mobile'],
                    'create_time'      => time(),
                    'admin_id'         => session('admins_id'),
                    'remarks'          => $remarks
                ];
                $res  = (new AnchorChangeMobileLogModel)->insert($data);
                if(!$res){
                    return json(['code' => -1, 'msg' => '变更失败', 'data' => '']);
                }
                //变更主表数据
                AnchorModel::where('id',$member->id)->update([
                    "mobile"        =>$param['after_mobile'],
                    "update_time"   =>time()
                ]);
                if($afterMemberMobile){
                    AnchorModel::where('id',$afterMember->id)->update([
                        "mobile"        =>$param['front_mobile'],
                        "update_time"   =>time()
                    ]);
                }
                return json(['code' => 0, 'msg' => '变更成功', 'data' => '']);
            }catch (\Exception $e){
                return json(['code'=>-1,'msg'=>'变更失败']);
            }
        } else {
            $mobile=$request->param('mobile','');
            $data['cols'] = [
                ['field' => 'front_mobile', 'title' => '原手机号','desc'=>'请输入原手机号'],
                ['field' => 'after_mobile', 'title' => '换绑后手机号','desc'=>'请输入换绑后手机号'],
            ];
            $data['title'] = $this->title;
            $data['create_url'] = '/backmanage/' . $this->route_alias . '/create';
            $data['mobile']=$mobile;
            return View::fetch('anchor_change_mobile/add', $data);
        }
    }

    //检测手机号状态提示
    public function checkMobileStatusTip(Request $request)
    {
        if ($request->isPost()) {
            $param    = $request->all();
            $type=$param['type']??0;
            if (empty($param['front_mobile']) && $type==1) {
                return json(['code'=>-1,'msg'=>'原手机号不能为空']);
            }
            if (empty($param['after_mobile']) && $type==2) {
                return json(['code'=>-1,'msg'=>'换绑后手机号不能为空']);
            }
            if ($type==1){
                $member=AnchorModel::where([
                    'mobile' => $param['front_mobile'],
                    'status' =>1
                ])->order('id','desc')->find();
                if (empty($member->id)) {
                    return json(['code'=>2,'msg'=>'该手机号未注册']);
                }
                //获取分区数据
                $partitionInfo=\app\common\model\common\PartitionPackage::where([
                    'partition_id'=>$member['partition_id'],
                    'status'=>1
                ])->find();
                if(empty($partitionInfo->id)){
                    Json::error('分区ID无效，请重试');
                }
                $subMemberModel=getSwitchDatabaseModel(sprintf("partition_%s",$partitionInfo['partition_id']),$partitionInfo['api_mysql_host_name'],$partitionInfo['api_mysql_database'],$partitionInfo['api_mysql_username'],$partitionInfo['api_mysql_password'],$partitionInfo['api_mysql_hostport']);
                $nickname=$subMemberModel->table('member')->where([
                    'mobile' => $member['mobile'],
                    'status' =>1
                ])->value('nickname');
                return json(['code'=>1,'msg'=>sprintf("所在分区：%s | 主播昵称：%s",$partitionInfo['partition_id'],$nickname)]);
            }else{
                $member=AnchorModel::where([
                    'mobile' => $param['after_mobile'],
                    'status' =>1
                ])->order('id','desc')->find();
                if (empty($member->id)) {
                    return json(['code'=>2,'msg'=>'未注册可换绑']);
                }
                //获取分区数据
                $partitionInfo=\app\common\model\common\PartitionPackage::where([
                    'partition_id'=>$member['partition_id'],
                    'status'=>1
                ])->find();
                if(empty($partitionInfo->id)){
                    Json::error('分区ID无效，请重试');
                }
                $subMemberModel=getSwitchDatabaseModel(sprintf("partition_%s",$partitionInfo['partition_id']),$partitionInfo['api_mysql_host_name'],$partitionInfo['api_mysql_database'],$partitionInfo['api_mysql_username'],$partitionInfo['api_mysql_password'],$partitionInfo['api_mysql_hostport']);
                $nickname=$subMemberModel->table('member')->where([
                    'mobile' => $member['mobile'],
                    'status' =>1
                ])->value('nickname');
                return json(['code'=>1,'msg'=>sprintf('所在分区：%s | 主播昵称：%s | 已注册，两者帐号可互换手机号',$partitionInfo['partition_id'],$nickname)]);
            }
        }
        return json(['code'=>-1,'msg'=>'请求类型错误']);
    }


}